import React, { useEffect, useMemo, useState } from 'react';
import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { message, Upload } from 'antd';
import PDFViewer from 'pdf-viewer-reactjs';
import Pdfviewer from 'pdfjs-dist';
import classnames from 'classnames/bind';
import styles from './index.module.scss';
const cn = classnames.bind(styles);

const { Dragger } = Upload;

interface SignatureData {
  accessKeyId?: string;
  host?: string;
  policy?: string;
  signature: string;
}

const App = () => {
  const [loaded, setLoaded] = useState(false);
  const [signatureData, setSignatureData] = useState<SignatureData>()
  const [showPdf, setShowPdf] = useState(false)
  const [pdfUrl, setPdfUrl] = useState('')

  useEffect(() => {
    // react只渲染一次
    if (loaded) return;
    setLoaded(true)
    // handleUpload()
    // console.log(123)
  }, [])

  async function getOSSSignature() {
    const response = await fetch("https://oss.chengyishi.online/");
    const data = await response.json();
    return data;
  }

  // 执行文件上传
  async function uploadFile(file: any, signatureData: any, onProgress: any, onSuccess: any, onError: any) {
    const formData = new FormData();
    // 这里添加所有需要的字段，与后端 Worker 返回的保持一致
    const fileKey = "project/tender/" + file.name; // 根据您 OSS 的命名规则自定义 key
    formData.append("key", fileKey);
    formData.append("OSSAccessKeyId", signatureData.accessKeyId);
    formData.append("policy", signatureData.policy);
    formData.append("Signature", signatureData.signature);
    formData.append("success_action_status", "200"); // OSS 成功上传后返回的 HTTP 状态码
    formData.append("file", file);
    console.log('看看formData', formData)

    try {
      const response = await fetch(signatureData.host, {
        method: "POST",
        body: formData,
      });

      if (response.ok) {
        console.log("上传成功！");
        onSuccess("ok", file);
        // showNotification("上传成功！");
        console.log('上传地址', "https://oss.chengyishi.com" + "/" + fileKey)
        setShowPdf(true)
        setPdfUrl("https://oss.chengyishi.com" + "/" + fileKey)
        // window.open("https://oss.chengyishi.com" + "/" + fileKey, '_blank')
        // displaySuccessMessage(

        // );
      } else {
        onError(response.statusText)
        console.log("上传失败！", response.status);
        // showNotification("上传失败！");
        alert("上传失败：" + response.statusText);
      }
    } catch (error: any) {
      onError(error)
      console.error("上传错误: ", error);
      alert("上传错误：" + error.message);
    }
  }

  const handleUpload = async (file: any, onProgress: any, onSuccess: any, onError: any) => {
    const signatureData = await getOSSSignature();
    await uploadFile(file, signatureData, onProgress, onSuccess, onError);
    console.log('signatureData', signatureData)
  }

  const props: UploadProps = useMemo(() => {
    return {
      name: 'file',
      multiple: true,
      customRequest: (fileObj: any) => {
        // debugger
        // console.log('fileObj', file.file)
        const { file, onProgress, onSuccess, onError } = fileObj;
        const uploadTask = handleUpload(file, onProgress, onSuccess, onError)
        // // 处理上传进度
        // onProgress({ percent: 50 }); // 假设上传进度为 50%

        // // 处理上传成功
        // onSuccess("ok", file);

        // // 处理上传失败
        // onError(new Error("Failed to upload"));

        // return {
        //   abort: () => {
        //     console.log('Aborting upload');
        //     uploadTask.abort();
        //   }
        // };
      },
      onChange(info) {
        console.log('info', info)
        // handleUpload(info.file)
        const { status } = info.file;
        if (status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (status === 'done') {
          message.success(`${info.file.name} 文件上传成功`);
        } else if (status === 'error') {
          message.error(`${info.file.name} 文件上传失败`);
        }
      },
      onDrop(e) {
        console.log('删除文件', e.dataTransfer.files);
      },
    }
  }, [signatureData]);

  return (
    <>
      <Dragger {...props} className={cn()}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">点击或拖动文件到此区域以上传</p>
        <p className="ant-upload-hint">
          支持单个或批量上传。
        </p>
      </Dragger>
      {/* <div className="App">
        <PdfViewer pdf={pdfUrl}
          onCancel={() => setShowPdf(false)}
          visible={showPdf}
        />
      </div> */}
      {pdfUrl ? (
        <PDFViewer
          document={{ url: pdfUrl }}
          // onCancel={() => setShowPdf(false)}
          // visible={showPdf}
        />
        // <Pdfviewer />
      ) : null}
    </>
  )
};

export default App;